let editor = function () {

    //根据DOM元素的id构造出一个编辑器
    var editor=CodeMirror.fromTextArea(document.getElementById("code"),{
        mode:"text/c-mysql", //实现mysql代码高亮
        lineNumbers:true,
        theme:"default",
        keyMap: "default",
        extraKeys:{"Tab":"autocomplete"},
        hint: CodeMirror.hint.sql,
        lineWrapping: true,         //是否换行
        foldGutter: true,           //是否折叠
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], //添加行号栏，折叠栏
        hintOptions: {
            tables: tablewords
        }

    });

    editor.on("keydown", function (cm, event) {
        if (event.keyCode === 27) {
            // 如果按esc则提示
            commandsAutocomplete(cm)
            return
        }
    })
    editor.on("keyup", function (cm, event) {
        if (window.load_page === "create_table_sql") {
            return
        }
        if (editor.getValue().length === 0) {
            return
        }
        // 禁用粘贴
        if (event.ctrlKey && event.keyCode === 86){
            return
        }
        //所有的字母在键松开之后都将触发自动完成
        if (event.keyCode >= 65 && event.keyCode <= 90 ) {

            commandsAutocomplete(cm)
            return
        }
        if (event.keyCode === 192) {
            // 如果按`则提示
            commandsAutocomplete(cm)
            return
        }
    });

    function commandsAutocomplete(cm) {
        cm.options.hintOptions.tables = tablewords
        CodeMirror.commands.autocomplete(cm, null, {
            completeSingle: false
        });
    }

    /**
     * 根据sql编辑框动态高度，设置表格的高度
     */
    function setDatalistHeight() {

        if($('.right-card .layui-tab').css("display")==="none"){// 第一次执行代码
            $("#handle").show();
            $('.right-card .layui-tab').show();
            editor.setSize('height','1200px');
        }
        var allH =  parseInt( $('.card').height());
        var sqlDivHeight = parseInt( $('.right-card .sql-div').height());
        var toolsDivHeight = parseInt( $('.right-card .tools').height());
        var datalistH = allH -sqlDivHeight- toolsDivHeight-32;
        $('.right-card .data-div').height(datalistH +'px');
        if($(".data-list .datagrid").length>0){// 数据表格存在是高度适用
            $('#sqldata').datagrid('resize', {
                height :datalistH-33+"px"
            })
        }

    }

    /**
     * 加载中...
     */
    function loading() {
        $("#stopImg").attr("src","image/stop1.png");
        $("#loading").show();
    }

    /**
     * 完成
     */
    function complete() {
        $("#loading").hide();
        $("#stopImg").attr("src","image/stop0.png");
    }
    var exeAjax;// 当前ajax请求;
    // 异步加载数据
    function stopLoadData() {
        if(exeAjax) {
            exeAjax.abort();
        }
    }
    //editor.setSize('height','200px');
    // 最小高度
    var MIN_HEIGHT = 100;

    //对编辑器这个node添加鼠标事件
    var editorNode = document.getElementById('code');

    var hahahha = document.getElementsByClassName('CodeMirror-wrap')[0];
    console.log('初始值：' + hahahha.offsetHeight);
    //
    var dragBar = document.getElementById('handle');

    // 返回编辑器的高度
    function  getHeight(node){
        var h =  window.getComputedStyle(node, null).height.replace(/px$/, "");
        if(h === 'auto'){
            h = node.offsetHeight;
        }
        return parseInt(h);
    }

    // 释放鼠标的时候触发的事件
    function release(){

        console.log('end');
        // 删除和添加都是使用两个参数的
        document.body.removeEventListener('mousemove', drag);
        window.removeEventListener('mouseup', release);

    }

    // drag 事件
    function drag(e){
    /*    console.log('drag');
        console.log('e.y:' + e.y);
        console.log('pos_y:' + pos_y);
        console.log('startHeight:' + startHeight);
        console.log('-----------');
        console.log(startHeight + e.y - pos_y);*/
        editor.setSize('height', Math.max(MIN_HEIGHT, (startHeight + e.y - pos_y)) + "px");
        setDatalistHeight();// 数据表格高度
    }

    dragBar.addEventListener('mousedown', function (e){
        console.log('start');
        // 开始高度
        startHeight =  getHeight(hahahha);
        console.log('开始高度：' + startHeight);
        pos_x = e.x;
        pos_y = e.y;



        //只有按下鼠标移动的时候才能移动
        document.body.addEventListener('mousemove', drag);
        window.addEventListener('mouseup', release);
    });


    function getSelectedRange() {
        return { from: editor.getCursor(true), to: editor.getCursor(false) };
    }


    /**
     * 格式化SQL
     */
    window.custom_format_sql = function (isBool = false) {
        // 获取输入的值
        console.log(editor.getValue());
        console.log('范围：' + JSON.stringify(getSelectedRange()));
        // var range = getSelectedRange();
        // editor.autoFormatRange(range.from, range.to);
        if (isBool) {

            let sql_str = sqlFormatter.format(editor.getValue(), {language: 'sql'}) + ';'
            editor.setValue(sql_str);
            console.log('格式化的代码:' + sql_str);
        }

        function format() {
            console.time('formatting');
            let sql_str = editor.getValue()
            let sql_array = sql_str.split(';')
            if (sql_array[sql_array.length - 1] === '') {
                sql_array.pop()
            }
            for (let i = 0; i < sql_array.length; i++) {
                    let func = function (item) {
                        if (item.length === 0) {

                            return item
                        }
                        let pos = -1, str1 = '', str2 = ''
                        for(let i = 0; i < item.length; i++) {
                            if (-1 === [' ', "\n"].indexOf(item[i])) {
                                pos = i
                                break
                            }
                        }
                        if (pos === -1) {
                            str1 = ''
                            str2 = item
                        } else {
                            str1 = item.substr(0, pos)
                            str2 = item.substr(pos)
                        }
                        let result = str1 + sqlFormatter.format(str2, {language: 'sql'}) + ';'
                        if ("\n" === result[0]) {

                            return result.substr(1)
                        }
                        return result
                }
                sql = func(sql_array[i])
                sql_array[i] = sql
            }
            editor.setValue(sql_array.join("\n"));
            console.log('格式化的代码:' + sql_array);
            console.timeEnd('formatting');
        }
        format();
    }

    window.get_from_and_to = function () {
        let cursor = editor.getCursor()
        let from = {line: 0, ch: 0}
        let to = {line: editor.lastLine(), ch: editor.getLine(editor.lastLine()).length}

        // 光标在行首
        // 向前查询上一个分号
        if (0 === cursor.ch) {
            if (0 === cursor.line) {
                from = cursor
            } else {
                for(let i = cursor.line; i >= 0; i--) {
                    let index;
                    if (i === cursor.line) {
                        index = editor.getLine(i).substr(0, to.ch - 1).indexOf(';')
                    } else {
                        index = editor.getLine(i).indexOf(';')
                        index = index == -1 ? -1 : index + 1
                    }
                    if (index >= 0) {
                        from = {line: i, ch: index}
                        break
                    }
                }
            }

            for(let i = cursor.line; i <= editor.lastLine(); i++) {
                let index = editor.getLine(i).indexOf(';')
                if (index >= 0) {
                    to = {line: i, ch: index}
                    break
                }
            }
            return {from: from, to: to}
        }
        // 光标在行尾
        if (editor.getLine(cursor.line).length === cursor.ch) {
            if (';' === editor.getLine(cursor.line).substr(cursor.ch - 1, cursor.ch)) {
                to = {line: cursor.line, ch: cursor.ch - 1}
            } else {
                for(let i = (cursor.line + 1); i <= editor.lastLine(); i++) {
                    let index = editor.getLine(i).indexOf(';')
                    if (index >= 0) {
                        to = {line: i, ch: index}
                        break
                    }
                }
            }

            for(let i = cursor.line; i >= 0; i--) {
                let index;
                if (i === cursor.line) {
                    index = editor.getLine(i).substr(0, to.ch - 1).indexOf(';')
                } else {
                    index = editor.getLine(i).indexOf(';')
                    index = index == -1 ? -1 : index + 1
                }
                if (index >= 0) {
                    from = {line: i, ch: index}
                    break
                }
            }
            return {from: from, to: to,}
        }

        // 光标在行中
        for(let i = cursor.line; i <= editor.lastLine(); i++) {
            let index = editor.getLine(i).indexOf(';')
            if (index >= 0) {
                to = {line: i, ch: index}
                break
            }
        }

        for(let i = cursor.line; i >= 0; i--) {
            let index;
            if (i === cursor.line) {
                index = editor.getLine(i).substr(0, to.ch - 1).indexOf(';')
                if (index >= 0) {
                    from = {line: i, ch: index}
                    break
                }
            } else {
                index = editor.getLine(i).indexOf(';')
                if (index >= 0) {
                    from = {line: i, ch: index + 1}
                    break
                }
            }
        }
        return {from: from, to: to,}
    }

    window.set_sql = function (sql) {
        console.log(sql)
        editor.setValue(sql)
        custom_format_sql(true)
        editor.setOption('readOnly', true)
    }

    window.get_sql = function () {
        // 是否有选中
        // 如果有选中，则返回选中行
        // 如果没有选中，则返回光标所在行的上下文SQL
        let sql = editor.getSelection()
        if (sql.length !== 0) {

            sql_py.js_set_sql(sql, function (res) {
                // alert(sql)
            })
            return sql
        }
        let pos = get_from_and_to()
        sql = editor.getRange(pos.from, pos.to)
        sql_py.js_set_sql(sql, function (res) {
            // alert(sql)
        })
        return sql
    }
    window.set_all_table_and_column = function (res) {
        window.tablewords = res
    }

    // 初始化数据库表树结构
    var tmp = function() {
        editor.refresh();
    };
    setTimeout(tmp, 100);

    /**** 初始化***/
    // 格式化
    $('#format').click(function () {
        custom_format_sql()
    });

}

let editorInterval = setInterval(function () {
    if ('string' == typeof tablewords) {
        return
    }
    console.log('tablewords is inited')
    clearInterval(editorInterval)
    editor()
}, 500)

let loadPageInterval = setInterval(function () {
    if (window.load_page === undefined) {
        if (window.sql_py === undefined) {
            return
        }
        sql_py.get_load_page('', function (res) {
            window.load_page = res
        })
        return
    }
    clearInterval(loadPageInterval)
}, 100)
